package com.hzncc.scaffold.controller.Rear.User;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzncc.scaffold.core.ResultT;
import com.hzncc.scaffold.entity.Bo.InstitutionalUserListBo;
import com.hzncc.scaffold.entity.Other.*;
import com.hzncc.scaffold.entity.Vo.AddInstituteUserVo;
import com.hzncc.scaffold.entity.Vo.InstitutionalUserListVo;
import com.hzncc.scaffold.entity.Vo.UpdateInstitutionalUserVo;
import com.hzncc.scaffold.entity.Vo.UserIdVoPlus;
import com.hzncc.scaffold.mapper.ApplianceapplyMapper;
import com.hzncc.scaffold.mapper.UserMapper;
import com.hzncc.scaffold.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Author: DrunkBear
 * @Date: 2022-05-23 19:04
 * @Description: null
 */
@RestController
@RequestMapping("/manage/instituteUser")
@Api(tags = "后台用户管理-机构用户")
public class InstitutionalUserController {

    @Autowired
    UsertagService usertagService;

    @Autowired
    UserService userService;

    @Autowired
    TagService tagService;

    @Autowired
    ApplianceapplyService applianceapplyService;

    @Autowired
    ApplianceapplyMapper applianceapplyMapper;

    @Autowired
    SiteapplyService siteapplyService;

    @Autowired
    UserMapper userMapper;

//    @GetMapping("/list")
//    @ApiOperation("机构用户列表")
//    public ResultT list(Integer pageNum, Integer pageSize, Integer type, Integer status, String keyword) {
//        ArrayList<InstitutionalUserListVo> institutionalUserListVos = new ArrayList<>();
//        LambdaQueryWrapper<Usertag> lqw = new LambdaQueryWrapper<>();
//        if (type != null) {
//            if (type == 0) {
//                lqw.eq(Usertag::getTagId, 7);
//            }
//            if (type == 1) {
//                lqw.eq(Usertag::getTagId, 11);
//            }
//        } else {
//            return ResultT.fail("数据错误");
//        }
//        if (pageNum != null && pageSize != null && pageNum > 0 && pageSize > 0) {
//            PageHelper.startPage(pageNum, pageSize);
//        }
//        List<Usertag> usertagList = usertagService.list(lqw);
//        for (Usertag usertag : usertagList) {
//
//            ArrayList<TagsVo> tags = new ArrayList<>();
//
//            if (userService.getById(usertag.getUserId()) != null) {
//                User user = userService.getById(usertag.getUserId());
//
//                if (user.getIsDelete()) {
//                    continue;
//                }
//
//                if (!StrUtil.contains(user.getName(), keyword)) {
//                    continue;
//                }
//                InstitutionalUserListVo institutionalUserListVo = BeanUtil.toBean(user, InstitutionalUserListVo.class);
//                institutionalUserListVo.setIsAlliance(false);
//                institutionalUserListVo.setIsExamSite(false);
//                institutionalUserListVo.setIsTrialSite(false);
//                institutionalUserListVo.setIsChargeSite(false);
//
//                String name = "";
//                if (tagService.getById(usertag.getTagId()) != null) {
//                    name = tagService.getById(usertag.getTagId()).getName();
//                }
//
//
//                List<Integer> instituteIdList = applianceapplyMapper.instituteIdList();
//                if (CollUtil.contains(instituteIdList, usertag.getUserId())) {
//                    institutionalUserListVo.setIsAlliance(true);
//                }
//
//                LambdaQueryWrapper<Siteapply> lqww = new LambdaQueryWrapper<>();
//                lqww.eq(Siteapply::getStatus, 1);
//                lqww.eq(Siteapply::getInstituteId, usertag.getUserId());
//                List<Siteapply> siteapplyList = siteapplyService.list(lqww);
//                for (Siteapply siteapply : siteapplyList) {
//                    if (siteapply.getType() == 0) {
//                        institutionalUserListVo.setIsTrialSite(true);
//                    }
//                    if (siteapply.getType() == 1) {
//                        institutionalUserListVo.setIsExamSite(true);
//                    }
//                    if (siteapply.getType() == 2) {
//                        institutionalUserListVo.setIsChargeSite(true);
//                    }
//                }
//
//                TagsVo tagsVo = new TagsVo();
//                tagsVo.setId(usertag.getTagId());
//                tagsVo.setName(name);
//                tags.add(tagsVo);
//
//                institutionalUserListVo.setTags(tags);
//                institutionalUserListVos.add(institutionalUserListVo);
//            }
//        }
//        return ResultT.success(institutionalUserListVos);
//    }


    @GetMapping("/list")
    @ApiOperation("机构用户列表")
    public ResultT list(Integer pageNum, Integer pageSize, String keyword, Integer type, Integer status) {
        QueryWrapper<InstitutionalUserListBo> qw = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(keyword)) {
            qw.like("user.name", keyword);
        }
        if (type == 0) {
            qw.eq("user.role", "学校");
        }
        if (type == 1) {
            qw.eq("user.role", "企业");
        }
        qw.eq("user.isDelete", false);

        if (pageNum != null && pageSize != null && pageNum > 0 && pageSize > 0) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<InstitutionalUserListBo> institutionalUserListBos = userMapper.institutionalUserList(qw);
        ArrayList<InstitutionalUserListVo> institutionalUserListVos = new ArrayList<>();

        for (InstitutionalUserListBo institutionalUserListBo : institutionalUserListBos) {
            InstitutionalUserListVo institutionalUserListVo = BeanUtil.toBean(institutionalUserListBo, InstitutionalUserListVo.class);

            LambdaQueryWrapper<Applianceapply> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Applianceapply::getInstituteId, institutionalUserListBo.getId());
            lqw.eq(Applianceapply::getStatus, 1);
            if (CollUtil.isNotEmpty(applianceapplyService.list())) {
                institutionalUserListVo.setIsAlliance(true);
            } else {
                institutionalUserListVo.setIsAlliance(false);
            }

            LambdaQueryWrapper<Siteapply> lqww = new LambdaQueryWrapper<>();
            lqww.eq(Siteapply::getInstituteId, institutionalUserListBo.getId());
            lqww.eq(Siteapply::getStatus, 1);
            lqww.eq(Siteapply::getType, 0);

            if (CollUtil.isNotEmpty(siteapplyService.list(lqww))) {
                institutionalUserListVo.setIsTrialSite(true);
            } else {
                institutionalUserListVo.setIsTrialSite(false);
            }

            LambdaQueryWrapper<Siteapply> lqwww = new LambdaQueryWrapper<>();
            lqwww.eq(Siteapply::getInstituteId, institutionalUserListBo.getId());
            lqwww.eq(Siteapply::getStatus, 1);
            lqwww.eq(Siteapply::getType, 1);

            if (CollUtil.isNotEmpty(siteapplyService.list(lqwww))) {
                institutionalUserListVo.setIsExamSite(true);
            } else {
                institutionalUserListVo.setIsExamSite(false);
            }

            LambdaQueryWrapper<Siteapply> lqwwww = new LambdaQueryWrapper<>();
            lqwwww.eq(Siteapply::getInstituteId, institutionalUserListBo.getId());
            lqwwww.eq(Siteapply::getStatus, 1);
            lqwwww.eq(Siteapply::getType, 2);

            if (CollUtil.isNotEmpty(siteapplyService.list(lqwwww))) {
                institutionalUserListVo.setIsChargeSite(true);
            } else {
                institutionalUserListVo.setIsChargeSite(false);
            }

            ArrayList<Tag> tags = new ArrayList<>();

            LambdaQueryWrapper<Usertag> lqwwwwww = new LambdaQueryWrapper<>();
            lqwwwwww.eq(Usertag::getUserId, institutionalUserListBo.getId());
            List<Usertag> usertagList = usertagService.list(lqwwwwww);

            for (Usertag usertag : usertagList) {
                Tag tag = tagService.getById(usertag.getTagId());
                tags.add(tag);
            }

            institutionalUserListVo.setTags(tags);
            institutionalUserListVos.add(institutionalUserListVo);
        }
//        PageInfo<InstitutionalUserListVo> info = new PageInfo<>();
//        info.setList(institutionalUserListVos);
//        info.setTotal(new PageInfo<>(institutionalUserListBos).getTotal());

        HashMap<String,Object> map = new HashMap<>();
        map.put("rows",institutionalUserListVos);
        map.put("count",new PageInfo<>(institutionalUserListBos).getTotal());
        return ResultT.success(map);
    }

    @PostMapping("/update")
    @ApiOperation("修改机构用户")
    public ResultT update(@RequestBody UpdateInstitutionalUserVo updateInstitutionalUserVo) {
        if (userService.getById(updateInstitutionalUserVo.getUserId()) == null) {
            return ResultT.fail("数据错误");
        }
        User user = BeanUtil.toBean(updateInstitutionalUserVo, User.class);
        user.setId(updateInstitutionalUserVo.getUserId());
        boolean update = userService.updateById(user);
        if (update) {
            return ResultT.success("修改成功");
        } else {
            return ResultT.fail("修改失败");
        }
    }

    @PostMapping("/delete")
    @ApiOperation("删除机构用户")
    public ResultT delete(@RequestBody UserIdVoPlus userIdVoPlus) {

        Integer userId = userIdVoPlus.getUserId();

        if (userService.getById(userId) == null) {
            return ResultT.fail("数据错误");
        }
        User user = userService.getById(userId);
        user.setIsDelete(true);
        boolean update = userService.updateById(user);
        if (update) {
            LambdaQueryWrapper<Usertag> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Usertag::getUserId, userId);
            usertagService.remove(lqw);
            return ResultT.success("删除成功");
        } else {
            return ResultT.fail("删除失败");
        }
    }

//    @PostMapping("/delete")
//    @ApiOperation("删除机构用户")
//    public ResultT delete(List<Integer> userId) {
//
//        try {
//            for (Integer id : userId) {
//                if (userService.getById(id) == null) {
//                    return ResultT.fail("数据错误");
//                }
//                User user = userService.getById(id);
//                user.setIsDelete(true);
//                boolean update = userService.updateById(user);
//                LambdaQueryWrapper<Usertag> lqw = new LambdaQueryWrapper<>();
//                lqw.eq(Usertag::getUserId, userId);
//                usertagService.remove(lqw);
//            }
//        } catch (Exception exception) {
//            exception.printStackTrace();
//            return ResultT.fail("数据错误");
//        }
//        return ResultT.success("删除成功");
//    }


    @GetMapping("/checkTelephone")
    @ApiOperation("检查号码是否存在")
    public ResultT checkTelephone(String telephone) {

        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();

        lqw.eq(telephone != null, User::getTelephone, telephone);
        List<User> userList = userService.list(lqw);

        if (CollUtil.isNotEmpty(userList)) {
            return ResultT.fail("该号码已存在");
        } else {
            return ResultT.success("该号码不存在");
        }
    }

    @PostMapping("/add")
    @ApiOperation("新增机构用户")
    public ResultT add(@RequestBody AddInstituteUserVo addInstituteUserVo) {
        if (!PhoneUtil.isMobile(addInstituteUserVo.getTelephone())) {
            return ResultT.fail("手机号码错误");
        }

        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StrUtil.isNotEmpty(addInstituteUserVo.getTelephone()), User::getTelephone, addInstituteUserVo.getTelephone());
        List<User> userList = userService.list(lqw);
        if (CollUtil.isNotEmpty(userList)) {
            return ResultT.fail("该号码已存在");
        }
        User user = BeanUtil.toBean(addInstituteUserVo, User.class);

        String gensalt = BCrypt.gensalt();
        String substring = StrUtil.sub(addInstituteUserVo.getTelephone(), -6, addInstituteUserVo.getTelephone().length());
        String hashpw = BCrypt.hashpw(substring, gensalt);

        user.setPassword(hashpw);
        user.setCreateTime(DateUtil.date());
        user.setAccount(DateUtil.current() + "");
        user.setInfo("");

        if (addInstituteUserVo.getType() == 0) {
            user.setRole("学校");
        }
        if (addInstituteUserVo.getType() == 1) {
            user.setRole("企业");
        }

        boolean save = userService.save(user);

        if (save) {
            return ResultT.success("新增成功");
        } else {
            return ResultT.fail("新增失败");
        }
    }

    @GetMapping("/exportUser")
    @ApiOperation("导出企业用户")
    public void exportUser(Integer type, HttpServletResponse response) throws IOException {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        if (type == 0) {
            lqw.eq(User::getRole, "学校");
        }
        if (type == 1) {
            lqw.eq(User::getRole, "企业");
        }
        lqw.eq(User::getIsDelete,0);
        lqw.orderByAsc(User::getId);
        List<User> userList = userService.list(lqw);
        ArrayList<Map<String, Object>> exportUserVos = new ArrayList<>();

        for (User user : userList) {
            LinkedHashMap<String, Object> map = new LinkedHashMap<>();
            map.put("机构名称", user.getName());
            map.put("账号", user.getAccount());
            map.put("联系地址", user.getAddress());
            map.put("创建时间", user.getCreateTime());

            if (user.getStatus() == 0) {
                map.put("状态", "正常");
            }
            if (user.getStatus() == 1) {
                map.put("状态", "冻结");
            }
            exportUserVos.add(map);
        }

        if (CollUtil.isNotEmpty(exportUserVos)) {

            ExcelWriter writer = ExcelUtil.getWriter();
            writer.write(exportUserVos, true);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            String fileName = "";
            if (type == 0) {
                fileName = URLEncoder.encode("学校用户列表", "UTF-8");
            }
            if (type == 1) {
                fileName = URLEncoder.encode("企业用户列表", "UTF-8");
            }
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out);
            writer.close();
        }
    }
}
